import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Card,
  Form,
  Select,
  Row,
  Col,
  Checkbox,
  Button,
  Input,
  InputNumber,
  Radio,
  Table,
  Divider,
  Spin,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import { routerRedux } from 'dva/router';

import { getParamUrl } from '../../utils/formatDataSource';
import TextArea from 'antd/lib/input/TextArea';

const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const Option = Select.Option;
const CheckboxGroup = Checkbox.Group;

@connect(({ studentDetailConfig, loading }) => ({
  studentDetailConfig,
  loading: loading.models.studentDetailConfig,
}))
class StudentDetailConfig extends PureComponent {
  state = {
    selfDescription: '',
    selfDisabled: true,
    likeSubject: [],
    likeStyle: [],
    studentId: '',
  };
  componentDidMount = () => {
    const { dispatch, location: { search } } = this.props;
    const params = getParamUrl(search);
    this.setState({
      likeSubject: this.getLoveDatas(),
      likeStyle: this.getLikeStyleData(),
      studentId: params.studentId,
    });
    dispatch({
      type: 'studentDetailConfig/getStudentSources',
    });

    dispatch({
      type: 'studentDetailConfig/getInitStudentDetail',
      payload: {
        studentId: params.studentId,
      },
    }).then(() => {
      const { initData } = this.props.studentDetailConfig;
      const { setFieldsValue } = this.props.form;
      const styleArr = initData.likeStyle ? initData.likeStyle.map(i => i.id) : [];
      const selfDesc = initData.likeStyle ? initData.likeStyle.find(l => l.id === '6') : undefined;
      if (selfDesc) {
        this.setState({
          selfDisabled: false,
          selfDescription: selfDesc.value,
        });
      }
      setFieldsValue({
        name: initData.name,
        age: initData.age,
        sex: initData.sex,
        parentPhone: initData.parentPhone,
        phone: initData.phone,
        wchat: initData.wchat,
        qq: initData.qq,
        compulsory: initData.compulsory,
        area: initData.area,
        schoolName: initData.schoolName,
        grade: initData.grade,
        classCount: initData.classCount,
        gradeCount: initData.gradeCount,
        hopeSchool: initData.hopeSchool,
        school: initData.school,
        likeStyle: styleArr,
      });

      const { likeSubject } = this.state;
      const history = initData.likeSubject;
      if (history) {
        history.map(h => {
          const one = likeSubject.find(s => s.key === h.key);
          if (one) {
            one.disabled = false;
            one.weakKnowledge = h.weakKnowledge;
            one.currentScore = h.currentScore;
            one.finalScore = h.finalScore;
          }
        });
      }
      this.setState({
        likeSubject: [...likeSubject],
      });
    });
  };

  getBasicInfo = () => {};
  hasErrors = fieldsError => {
    return Object.keys(fieldsError).some(field => fieldsError[field]);
  };
  handleSubmit = e => {
    const { dispatch, location: { search } } = this.props;
    const params = getParamUrl(search);
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.selfDescription = this.state.selfDescription;
        const subjects = this.state.likeSubject.filter(s => s.disabled === false);
        values.likeSubject = subjects;
        values.studentId = params.studentId;

        const styleArr = this.state.likeStyle.filter(l => values.likeStyle.find(v => v === l.id));
        const selfDes = styleArr.find(s => s.id === '6');
        if (selfDes) {
          selfDes.value = this.state.selfDescription;
        }
        values.likeStyle = styleArr;
        dispatch({
          type: 'studentDetailConfig/saveUserInfo',
          payload: values,
        });
      }
    });
  };
  getLoveColumns = () => {
    return [
      {
        title: '学科',
        key: 'subject',
        render: item => {
          return (
            <Checkbox
              checked={!item.disabled}
              onChange={e => {
                if (e.target.checked) {
                  item.disabled = false;
                } else {
                  item.disabled = true;
                  item.weakKnowledge = '';
                  item.currentScore = '';
                  item.finalScore = '';
                }
                const { likeSubject } = this.state;
                this.setState({ likeSubject: [...likeSubject] });
              }}
            >
              {item.subject}
            </Checkbox>
          );
        },
      },
      {
        title: '薄弱知识',
        key: 'lowKnown',
        render: item => {
          return (
            <Input
              value={item.weakKnowledge}
              onChange={e => {
                item.weakKnowledge = e.target.value;
                const { likeSubject } = this.state;
                this.setState({ likeSubject: [...likeSubject] });
              }}
              disabled={item.disabled}
              maxLength={100}
            />
          );
        },
      },
      {
        title: '近期目标分数',
        key: 'recentScore',
        render: item => {
          return (
            <InputNumber
              value={item.currentScore}
              onChange={e => {
                item.currentScore = e;
                const { likeSubject } = this.state;
                this.setState({ likeSubject: [...likeSubject] });
              }}
              style={{ width: '100%' }}
              max={200}
              disabled={item.disabled}
            />
          );
        },
      },
      {
        title: '最终目标分数',
        key: 'featureScore',
        render: item => {
          return (
            <InputNumber
              value={item.finalScore}
              onChange={e => {
                item.finalScore = e;
                const { likeSubject } = this.state;
                this.setState({ likeSubject: [...likeSubject] });
              }}
              style={{ width: '100%' }}
              max={200}
              disabled={item.disabled}
            />
          );
        },
      },
    ];
  };
  getLoveDatas = () => {
    return [
      {
        subject: '数学',
        key: '1',
        disabled: true,
        weakKnowledge: '',
        currentScore: '',
        finalScore: '',
      },
      {
        subject: '语文',
        key: '2',
        disabled: true,
        weakKnowledge: '',
        currentScore: '',
        finalScore: '',
      },
      {
        subject: '英语',
        key: '3',
        disabled: true,
        weakKnowledge: '',
        currentScore: '',
        finalScore: '',
      },
      {
        subject: '物理',
        key: '4',
        disabled: true,
        weakKnowledge: '',
        currentScore: '',
        finalScore: '',
      },
      {
        subject: '化学',
        key: '5',
        disabled: true,
        weakKnowledge: '',
        currentScore: '',
        finalScore: '',
      },
      {
        subject: '生物',
        key: '6',
        disabled: true,
        weakKnowledge: '',
        currentScore: '',
        finalScore: '',
      },
      {
        subject: '地理',
        key: '7',
        disabled: true,
        weakKnowledge: '',
        currentScore: '',
        finalScore: '',
      },
      {
        subject: '历史',
        key: '8',
        disabled: true,
        weakKnowledge: '',
        currentScore: '',
        finalScore: '',
      },
      {
        subject: '政治',
        key: '9',
        disabled: true,
        weakKnowledge: '',
        currentScore: '',
        finalScore: '',
      },
    ];
  };
  handleSelfChange = e => {
    if (e.includes('6')) {
      this.setState({ selfDisabled: false });
    } else {
      this.setState({ selfDisabled: true });
    }
  };
  getLikeStyleData = () => {
    return [
      { id: '1', title: '风趣幽默型，能吸引我听课', value: '风趣幽默型，能吸引我听课' },
      {
        id: '2',
        title: '应式提分型，注重课堂效率，节奏紧凑，善于归纳总结',
        value: '应式提分型，注重课堂效率，节奏紧凑，善于归纳总结',
      },
      { id: '3', title: '铁面无私', value: '铁面无私' },
      { id: '4', title: '耐心解答', value: '耐心解答' },
      { id: '5', title: '年轻型', value: '年轻型' },
      { id: '6', title: '自由描述', value: '' },
    ];
  };
  backPage = () => {
    this.props.dispatch(
      routerRedux.push(`/studentManage/student/info?studentId=${this.state.studentId}`)
    );
  };

  render = () => {
    const { getFieldDecorator, getFieldsError } = this.props.form;

    const { menuData } = this.props.studentDetailConfig;
    return (
      <PageHeaderLayout>
        <Card style={{ minHeight: '920px' }}>
          <Spin tip="Loading..." spinning={this.props.loading}>
            <Form onSubmit={this.handleSubmit}>
              <Row>
                <Col span={12} style={{ fontSize: '18px' }}>
                  <strong>基础信息</strong>
                </Col>
                <Col span={12} style={{ textAlign: 'right' }}>
                  <Button type="primary" size="small" onClick={this.backPage}>
                    返回
                  </Button>
                </Col>
              </Row>
              <FormItem label="姓名" labelCol={{ span: '2' }} wrapperCol={{ span: 6 }}>
                {getFieldDecorator('name', {
                  rules: [
                    {
                      required: true,
                      message: '请输入姓名',
                    },
                  ],
                })(<Input maxLength={50} />)}
              </FormItem>
              <FormItem label="年龄" labelCol={{ span: '2' }} wrapperCol={{ span: 6 }}>
                {getFieldDecorator('age', {
                  rules: [
                    {
                      required: true,
                      message: '请输入年龄',
                    },
                  ],
                })(<InputNumber min={1} max={100} />)}
              </FormItem>
              <FormItem label="性别" labelCol={{ span: '2' }} wrapperCol={{ span: 6 }}>
                {getFieldDecorator('sex', {
                  rules: [
                    {
                      required: true,
                      message: '请输入性别',
                    },
                  ],
                })(
                  <RadioGroup>
                    <Radio value="男">男</Radio>
                    <Radio value="女">女</Radio>
                  </RadioGroup>
                )}
              </FormItem>
              <FormItem label="家长电话" labelCol={{ span: '2' }} wrapperCol={{ span: 6 }}>
                {getFieldDecorator('parentPhone', {
                  rules: [
                    { required: true, message: '请输入家长电话' },
                    { pattern: /^1\d{10}$/, message: '手机号格式不正确!' },
                  ],
                })(<Input maxLength={50} />)}
              </FormItem>
              <FormItem label="联系电话" labelCol={{ span: '2' }} wrapperCol={{ span: 6 }}>
                {getFieldDecorator('phone', {
                  rules: [
                    { required: true, message: '请输入联系电话' },
                    { pattern: /^1\d{10}$/, message: '手机号格式不正确!' },
                  ],
                })(<Input maxLength={50} />)}
              </FormItem>
              <FormItem label="微信" labelCol={{ span: '2' }} wrapperCol={{ span: 6 }}>
                {getFieldDecorator('wchat')(<Input maxLength={50} />)}
              </FormItem>
              <FormItem label="QQ" labelCol={{ span: '2' }} wrapperCol={{ span: 6 }}>
                {getFieldDecorator('qq')(<Input maxLength={50} />)}
              </FormItem>
              <FormItem label="必修课程" labelCol={{ span: '2' }} wrapperCol={{ span: 6 }}>
                {getFieldDecorator('compulsory', {
                  rules: [
                    {
                      required: true,
                      message: '请选择必修课',
                    },
                  ],
                })(
                  <CheckboxGroup style={{ width: '100%' }}>
                    <Row>
                      <Col span={8}>
                        <Checkbox value="1">数学</Checkbox>
                      </Col>
                      <Col span={8}>
                        <Checkbox value="2">语文</Checkbox>
                      </Col>
                      <Col span={8}>
                        <Checkbox value="3">英语</Checkbox>
                      </Col>
                      <Col span={8}>
                        <Checkbox value="4">物理</Checkbox>
                      </Col>
                      <Col span={8}>
                        <Checkbox value="5">化学</Checkbox>
                      </Col>
                      <Col span={8}>
                        <Checkbox value="6">生物</Checkbox>
                      </Col>
                      <Col span={8}>
                        <Checkbox value="7">地理</Checkbox>
                      </Col>
                      <Col span={8}>
                        <Checkbox value="8">历史</Checkbox>
                      </Col>
                      <Col span={8}>
                        <Checkbox value="9">政治</Checkbox>
                      </Col>
                    </Row>
                  </CheckboxGroup>
                )}
              </FormItem>
              <div style={{ fontSize: '18px' }}>
                <strong>学习信息</strong>
              </div>
              <FormItem label="所在地区" labelCol={{ span: '2' }} wrapperCol={{ span: 6 }}>
                {getFieldDecorator('area', {
                  rules: [
                    {
                      required: true,
                      message: '请选择所在地区',
                    },
                  ],
                })(
                  <Select style={{ width: 120 }} placeholder="请选择区域">
                    {menuData.area.map((a, i) => (
                      <Option value={a.id} key={i}>
                        {a.area}
                      </Option>
                    ))}
                  </Select>
                )}
              </FormItem>
              <FormItem label="学校名称" labelCol={{ span: '2' }} wrapperCol={{ span: 6 }}>
                {getFieldDecorator('schoolName', {
                  rules: [
                    {
                      required: true,
                      message: '请输入学校名称',
                    },
                  ],
                })(<Input maxLength={50} />)}
              </FormItem>
              <FormItem label="在读年级" labelCol={{ span: '2' }} wrapperCol={{ span: 6 }}>
                {getFieldDecorator('grade', {
                  rules: [
                    {
                      required: true,
                      message: '请选择在读年级',
                    },
                  ],
                })(
                  <Select style={{ width: 120 }} placeholder="请选择年级">
                    <Option value="一年级">一年级</Option>
                    <Option value="二年级">二年级</Option>
                    <Option value="三年级">三年级</Option>
                    <Option value="四年级">四年级</Option>
                    <Option value="五年级">五年级</Option>
                    <Option value="六年级">六年级</Option>
                    <Option value="初一">初一</Option>
                    <Option value="初二">初二</Option>
                    <Option value="初三">初三</Option>
                    <Option value="高一">高一</Option>
                    <Option value="高二">高二</Option>
                    <Option value="高三">高三</Option>
                  </Select>
                )}
              </FormItem>
              <FormItem label="班级人数" labelCol={{ span: '2' }} wrapperCol={{ span: 6 }}>
                {getFieldDecorator('classCount', {
                  rules: [
                    {
                      required: true,
                      message: '请输入班级人数',
                    },
                  ],
                })(<InputNumber min={1} max={100} style={{ width: '100%' }} />)}
              </FormItem>
              <FormItem label="年级人数" labelCol={{ span: '2' }} wrapperCol={{ span: 6 }}>
                {getFieldDecorator('gradeCount', {
                  rules: [
                    {
                      required: true,
                      message: '请输入年级人数',
                    },
                  ],
                })(<InputNumber min={1} max={100000} style={{ width: '100%' }} />)}
              </FormItem>
              <div style={{ fontSize: '18px' }}>
                <strong>需求信息</strong>
              </div>
              <FormItem label="意向学科" labelCol={{ span: '2' }} wrapperCol={{ span: 11 }}>
                {getFieldDecorator('likeSubject')(
                  <Table
                    dataSource={this.state.likeSubject}
                    columns={this.getLoveColumns()}
                    size="small"
                    pagination={{ hideOnSinglePage: true }}
                    bordered
                  />
                )}
              </FormItem>
              <FormItem label="目标学校" labelCol={{ span: '2' }} wrapperCol={{ span: 6 }}>
                {getFieldDecorator('hopeSchool', {
                  rules: [
                    {
                      required: true,
                      message: '请输入目标学校',
                    },
                  ],
                })(<Input maxLength={50} />)}
              </FormItem>
              <FormItem label="喜欢风格" labelCol={{ span: '2' }} wrapperCol={{ span: 11 }}>
                {getFieldDecorator('likeStyle', {
                  rules: [
                    {
                      required: false,
                    },
                  ],
                })(
                  <CheckboxGroup style={{ width: '100%' }} onChange={this.handleSelfChange}>
                    <Row>
                      {this.state.likeStyle.map((l, i) => {
                        if (i < this.state.likeStyle.length - 1) {
                          return (
                            <Col span={24} key={i}>
                              <Checkbox value={l.id}>{l.value}</Checkbox>
                            </Col>
                          );
                        }
                      })}
                      <Col span={4}>
                        <Checkbox value="6">自由描述:</Checkbox>
                      </Col>
                      <Col span={20}>
                        <TextArea
                          rows={4}
                          value={this.state.selfDescription}
                          onChange={e => this.setState({ selfDescription: e.target.value })}
                          disabled={this.state.selfDisabled}
                        />
                      </Col>
                    </Row>
                  </CheckboxGroup>
                )}
              </FormItem>
              <Divider />
              <FormItem label="录入校区" labelCol={{ span: '2' }} wrapperCol={{ span: 6 }}>
                {getFieldDecorator('school', {
                  rules: [
                    {
                      required: true,
                      message: '请选择录入校区',
                    },
                  ],
                })(
                  <Select style={{ width: 120 }} placeholder="选择校区">
                    {menuData.xiaoqu.map((a, i) => (
                      <Option value={a.id + ''} key={i}>
                        {a.name}
                      </Option>
                    ))}
                  </Select>
                )}
              </FormItem>
              <FormItem>
                <Button
                  type="primary"
                  htmlType="submit"
                  disabled={this.hasErrors(getFieldsError())}
                  style={{ width: '150px' }}
                >
                  提交
                </Button>
              </FormItem>
            </Form>
          </Spin>
        </Card>
      </PageHeaderLayout>
    );
  };
}
export default Form.create()(StudentDetailConfig);
